using System.Collections.Generic;

namespace OracleInternal.BulkCopy
{
	internal class BulkCopyBindingRow
	{
		private static Queue<BulkCopyBindingRow> s_bindingRowCache;

		private static object s_bindingRowCacheLock;

		private static int s_numCreated;

		internal int m_columnCount;

		internal byte[][] m_columnsBindValues;

		internal bool[] m_col_nullIndicators;

		internal int[] m_bindValuesLen;

		static BulkCopyBindingRow()
		{
			s_bindingRowCache = new Queue<BulkCopyBindingRow>();
			s_bindingRowCacheLock = new object();
		}

		internal static void AddToCache(BulkCopyBindingRow bindingRow)
		{
			bindingRow.Reset();
			lock (s_bindingRowCacheLock)
			{
				s_bindingRowCache.Enqueue(bindingRow);
			}
		}

		internal static void AddToCache(List<BulkCopyBindingRow> bindingRows)
		{
			lock (s_bindingRowCacheLock)
			{
				for (int i = 0; i < bindingRows.Count; i++)
				{
					bindingRows[i].Reset();
					s_bindingRowCache.Enqueue(bindingRows[i]);
				}
			}
		}

		internal static BulkCopyBindingRow GetFromCache(int columnCount)
		{
			lock (s_bindingRowCacheLock)
			{
				BulkCopyBindingRow bulkCopyBindingRow = null;
				if (s_bindingRowCache.Count > 0)
				{
					bulkCopyBindingRow = s_bindingRowCache.Dequeue();
					if (columnCount == bulkCopyBindingRow.m_columnCount)
					{
						return bulkCopyBindingRow;
					}
					bulkCopyBindingRow.Initialize(columnCount);
					return bulkCopyBindingRow;
				}
				return new BulkCopyBindingRow(columnCount);
			}
		}

		private BulkCopyBindingRow(int columnCount)
		{
			m_columnCount = columnCount;
			m_columnsBindValues = new byte[m_columnCount][];
			m_col_nullIndicators = new bool[m_columnCount];
			m_bindValuesLen = new int[m_columnCount];
		}

		internal void Reset()
		{
			for (int i = 0; i < m_columnCount; i++)
			{
				m_columnsBindValues[i] = null;
			}
		}

		internal void Initialize(int columnCount)
		{
			if (columnCount <= m_columnCount)
			{
				m_columnCount = columnCount;
				return;
			}
			m_columnCount = columnCount;
			m_columnsBindValues = new byte[m_columnCount][];
			m_col_nullIndicators = new bool[m_columnCount];
			m_bindValuesLen = new int[m_columnCount];
		}

		internal BulkCopyBindingRow Copy()
		{
			BulkCopyBindingRow fromCache = GetFromCache(m_columnCount);
			for (int i = 0; i < m_columnCount; i++)
			{
				fromCache.m_columnsBindValues[i] = m_columnsBindValues[i];
				fromCache.m_col_nullIndicators[i] = m_col_nullIndicators[i];
				fromCache.m_bindValuesLen[i] = m_bindValuesLen[i];
			}
			return fromCache;
		}
	}
}
